// a Simple loging system
// By DreamVB 19:12 28/09/2016

#include <iostream>
#include <fstream>
#include <Windows.h>

using namespace std;
using std::cout;
using std::endl;

fstream m_log;
string LogFile = "";

enum TLogcodes{
	Emergency=0,
	Alert,
	Critical,
	Error,
	Warning,
	Notice
};

bool FileExists(string filename){
	//Check if a file was found.
	if (GetFileAttributesA(filename.c_str()) == INVALID_FILE_ATTRIBUTES){
		return false;
	}
	return true;
}

string GetAppExeName(){
	wstring Ret;
	string s0 = "";
	int pos = 0;

	TCHAR fName[MAX_PATH];
	//Get full path and exe name.
	GetModuleFileName(NULL, fName, MAX_PATH);
	//Get wide string
	Ret = fName;
	//Get from from wide string
	s0 = string(Ret.begin(), Ret.end());
	//Locate last backslash
	pos = s0.find_last_of("\\");

	if (pos != string::npos){
		return s0.substr(pos + 1);
	}

	return s0;
}

bool CreateLogFile(){

	//Open log file for first time.
	m_log.open(LogFile.c_str(),ios::ios_base::out);

	if (!m_log.good()){
		return false;
	}

	//Write start of log
	m_log << endl;
	m_log << "-------------------------------------------------" << endl;
	m_log << "Appliaction: " << GetAppExeName().c_str() << endl;
	m_log << "-------------------------------------------------" << endl;
	m_log << endl;

	//Close file.
	m_log.close();
	//Write log name
	return true;
}

bool WriteToLog(TLogcodes code, string msg)
{
	//Get system time and date.
	SYSTEMTIME st;

	//Fetch system time.
	GetLocalTime(&st);

	//Open the file for apending
	m_log.open(LogFile.c_str(), ios::ios_base::app | ios::ios_base::out);

	if (!m_log.good()){
		return false;
	}

	//Output date and time and log message
	m_log << "Code    : " << code << endl <<
		"Date    : " << st.wDay << "/" << st.wMonth <<
		"/" << st.wYear << endl << "Time    : " << st.wHour <<
		":" << st.wMinute << ":" << st.wSecond <<
		endl << "Message : " << msg.c_str() << endl << endl;

	//Close file
	m_log.close();
	return true;
}

int main(int argc, char *argv[]){

	//Location of log file.
	LogFile = "C:\\ben\\log.txt";

	//If file is not here create it
	if (!FileExists(LogFile)){
		if (!CreateLogFile()){
			cout << "Error createing log file.." << endl;
			exit(1);
		}
	}

	//Write some logs
	WriteToLog(Alert, "File Not Found main.db");
	WriteToLog(Error,"Division by zero");
	WriteToLog(Notice, "Task was compleated");

	system("pause");
	return 0;
}